package goods

import (
	"context"
	"github.com/zeromicro/go-zero/core/limit"
	"mall-backend/api/internal/svc"
	"mall-backend/api/internal/types"
	"mall-backend/pkg/errorex"
	client "mall-backend/rpc/goods/client/goods"
	"net/http"
	"strconv"

	"github.com/zeromicro/go-zero/core/logx"
)

const (
	limitPeriod     = 10
	limitQuota      = 10000000000
	goodsListPrefix = "goods:list:"
)

type GoodsListLogic struct {
	logx.Logger
	ctx     context.Context
	svcCtx  *svc.ServiceContext
	limiter *limit.PeriodLimit
}

func NewGoodsListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GoodsListLogic {
	return &GoodsListLogic{
		Logger:  logx.WithContext(ctx),
		ctx:     ctx,
		svcCtx:  svcCtx,
		limiter: limit.NewPeriodLimit(limitPeriod, limitQuota, svcCtx.StoreRedis, goodsListPrefix),
	}
}

// 使用hey测试并发连接数
// hey -z 1s -c 110 -q 1 'http://localhost:8888/api/v1/goods/list'
// limiter 测试限流

func (l *GoodsListLogic) GoodsList(req *types.ListGoodsReq) (resp *types.ListGoodsResp, err error) {
	// todo: add your logic here and delete this line
	// time.Sleep(50 * time.Millisecond)
	code, _ := l.limiter.Take(strconv.FormatInt(5, 10))
	if code == limit.OverQuota {
		return nil, errorex.NewError(http.StatusBadRequest, errorex.C_OVER_LIMIT_ERR)
	}
	r, err := l.svcCtx.GoodsRpc.ListCategory(l.ctx, &client.ListCategoryReq{})
	if err != nil {
		logx.Error("GoodsList ListCategory err:", err)
	}
	logx.Info("GoodsList ListCategory result:", r)
	return &types.ListGoodsResp{
		ErrNo:  r.ErrNo,
		ErrMsg: r.ErrMsg,
	}, nil
}
